import store from '@/store'
import requestConfig from '@/config'
import { getAccessToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams } from '@/utils/common'
import modal from '@/plugins/modal'

let timeout = 20000

let originRequest = null
const request = config => {
  originRequest = config
  
	// 是否需要设置 token
	const isToken = (config.header || {}).isToken === false
	config.header = config.header || {}
	if (getAccessToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getAccessToken()
	}
	if (config.token) {
		config.header['Authorization'] = config.token
	}
	// 设置租户 TODO 芋艿：强制 1 先
	config.header['tenant-id'] = store.getters.currentTenantId
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		config.url = url.slice(0, -1)
	}
  if (config.baseUrl) {
    config.url = config.baseUrl
  } else if (config.baseApi) {
    config.url = requestConfig.baseUrl + config.baseApi + config.url
  } else {
    config.url = requestConfig.baseUrl + requestConfig.baseApi + config.url
  }
	return new Promise(async (resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.url,
				data: config.data,
				// header: config.header,
				header: config.header,
				sslVerify: false,
				dataType: 'json'
			}).then(response => {
				if (response.statusCode !== 200 || !response || !response.statusCode) {
					modal.msgError('后端接口连接异常')
					reject('后端接口连接异常')
				}
				const code = response.data.code || 200
				let msg = errorCode[code] || response.data.msg || errorCode['default']
				if (config.validAdminType && msg && msg.indexOf('负责人')) {
					msg = msg.replace('负责人', '法人')
				}
				if (code === 401) {
					modal.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(() => {
						store.dispatch('LogOut').then(() => {
              uni.reLaunch({
                url: '/pages/login'
              })
            })
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code === 500) {
					if (!config.hideErrorMessage) modal.msgError(msg)
					reject('500')
				} else if (code !== 200) {
					if (config.status === undefined) {
						if (!config.hideErrorMessage) modal.msgError(msg)
					}
					reject(response.data)
				}
				resolve(response.data)
			})
			.catch(error => {
				let {
					errMsg
				} = error
				if (errMsg === 'Network Error') {
					errMsg = '后端接口连接异常'
				} else if (errMsg.includes('timeout')) {
					errMsg = '系统接口请求超时'
				} else if (errMsg.includes('Request failed with status code')) {
					errMsg = '系统接口' + errMsg.substr(errMsg.length - 3) + '异常'
				}
				if (!config.hideErrorMessage) modal.msgError(errMsg)
				reject(error)
			})
	})
}

export default request